using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.IO;

namespace Services
{
	public interface ITrialService
	{
		short GamesLeft();
		void GameUsed();
	}

	public class TrialService : ITrialService
	{
		private const String FileName = "Trial.xml";
		private const short TrialGames = 3;

		private short trialGamesLeft;

		public TrialService() 
			: base()
		{
			if (!IsSaveAvailable())
			{
				trialGamesLeft = TrialGames;
				CreateTrialFile(TrialGames);
			}
			else trialGamesLeft = LoadTrialFile();
		}

		private void CreateTrialFile(short gameLeft)
		{
#if WINDOWS_PHONE
			IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
			IsolatedStorageFileStream stream = store.OpenFile(FileName, FileMode.Create, FileAccess.ReadWrite);
#else
			FileStream stream = File.Open(FileName, FileMode.Create);			
#endif 

			XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
			ns.Add("", "");
			
			XmlSerializer serializer = new XmlSerializer(typeof(short));
			serializer.Serialize(stream, gameLeft);

			stream.Close();

#if WINDOWS_PHONE
			store.Dispose();
#endif
		}

		private short LoadTrialFile()
		{
			if (!IsSaveAvailable())
			{
				// should not be here
				throw new Exception("Save Data File not found");
			}

#if WINDOWS_PHONE

			IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
			IsolatedStorageFileStream stream = store.OpenFile(FileName, FileMode.Open, FileAccess.Read);
#else
			FileStream stream = File.Open(FileName, FileMode.Open);
#endif
			
			XmlSerializer serializer = new XmlSerializer(typeof(short));
			short i = (short)serializer.Deserialize(stream);

			stream.Close();

#if WINDOWS_PHONE
			store.Dispose();
#endif

			return i;
		}

		private bool IsSaveAvailable()
		{
#if WINDOWS_PHONE
			IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
			return store.FileExists(FileName);
#else
			return File.Exists(FileName);
#endif
		}

		#region INTERFACE

		public short GamesLeft()
		{
			return trialGamesLeft; 
		}

		public void GameUsed()
		{
			trialGamesLeft -= 1;
			CreateTrialFile(trialGamesLeft);
		}

		#endregion
	}
}
